package com.tiger.web.controller.statistics;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.github.pagehelper.Page;
import com.tiger.common.core.controller.BaseController;
import com.tiger.common.core.domain.AjaxResult;
import com.tiger.common.core.domain.model.LoginUser;
import com.tiger.common.core.page.TableDataInfo;
import com.tiger.common.utils.ServletUtils;
import com.tiger.common.utils.spring.SpringUtils;
import com.tiger.framework.web.service.TokenService;
import com.tiger.project.domain.Asset;
import com.tiger.project.domain.vo.*;
import com.tiger.project.service.IAssetService;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 资产统计相关API请求控制类
 *
 * @author Lyn 宋开放
 * @date 2023-01-09 10:03
 **/
@RestController
@RequestMapping("statistics/asset")
public class AssetStatisticsController extends BaseController {

    private final IAssetService assetService;

    public AssetStatisticsController(IAssetService assetService) {
        this.assetService = assetService;
    }

    /**
     * 工作台-资产统计
     *
     * @return
     */
    @GetMapping("worktable/count")
    public AjaxResult listCount(@RequestParam("companyId") int companyId) {

        return AjaxResult.success(assetService.listCount(companyId) );
    }

    /**
     * 工作台-出租统计
     *
     * @return
     */
    @GetMapping("worktable/rent/count")
    public AjaxResult rentCount(@RequestParam("companyId") int companyId) {
        return AjaxResult.success(companyId);
    }

    /**
     * 工作台-合同数量统计
     * @return
     */
    @GetMapping("worktable/contract/count")
    public AjaxResult contractCount(@RequestParam("companyId") int companyId){
        return  AjaxResult.success(assetService.contractCount(companyId));
    }

    /**
     * 工作台-合同执行情况
     * @return
     */
    @GetMapping("worktable/contract/performance")
    public AjaxResult getPerformanceOfContract(@RequestParam("companyId") int companyId){
        return  AjaxResult.success(companyId);
    }
    /**
     * 工作台-合同逾期排名
     * @return
     */
    @GetMapping("worktable/contract/overdue/ranking")
    public AjaxResult getContractOverdueRanking(@RequestParam("companyId") int companyId){
        return  AjaxResult.success(companyId);
    }
    @GetMapping("idle/page")
    public TableDataInfo idlePage(Asset asset) {

        asset.setCompanyId(Long.valueOf(getCompanyId()));
        startPage();
        List<Asset> list = assetService.idlePage(asset);
        return getDataTable(list);
    }

    @SneakyThrows
    @GetMapping("idle/xlsx")
    public void idleExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/闲置资产明细-template.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("闲置资产明细", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.idleList(Long.valueOf(getCompanyId())));
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }

    @GetMapping("rent/page")
    public TableDataInfo rentPage() {
        startPage();
        List<RentAssetVO> list = assetService.rentPage(Long.valueOf(getCompanyId()));
        return getDataTable(list);
    }

    @GetMapping("rent/xlsx")
    public void rentExport(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        File directory = new File("src/main/resources");
        String reportPath = directory.getCanonicalPath();
        String resource = reportPath + "/template/减租、免租明细-template.xlsx";

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("减租、免租明细", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(resource).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照下一个
            List<RentAssetVO> rentAssetVOList = assetService.rentPage(Long.valueOf(getCompanyId()));
            FillConfig fillConfig = FillConfig.builder().build();
            excelWriter.fill(rentAssetVOList, fillConfig, writeSheet);
//            excelWriter.fill(data(), fillConfig, writeSheet);
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("currentYear", DateUtil.date().year());
            map.put("prevYear", DateUtil.date().year() - 1);
            excelWriter.fill(map, writeSheet);
        }
    }

    @GetMapping("monitor/statistics")
    public AssetStatisticsVO statistics() {
        Asset asset = new Asset();
        asset.setCompanyId(Long.valueOf(getCompanyId()));
        return this.assetService.getStatistics(asset);
    }

    @GetMapping("monitor/page")
    public TableDataInfo monitorAssetPage(Asset asset) {
        asset.setCompanyId(Long.valueOf(getCompanyId()));
        startPage();
        List<MonitorAssetVO> list = assetService.monitorAssetPage(asset);
        return getDataTable(list);
    }

    @GetMapping("land/xlsx")
    public void landExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/土地资产台账-template.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("土地资产台账", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.landExportList(Long.valueOf(getCompanyId())));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }

    @GetMapping("land/basic/page")
    public TableDataInfo landBasicPage() {
        startPage();
        List<AssetStatisticsBasicVO> list = this.assetService.landBasicPage(Long.valueOf(getCompanyId()));
        return getDataTable(list);
    }

    @GetMapping("land/used/page")
    public TableDataInfo landUsedPage() {
        startPage();
        List<AssetStatisticsUsedVO> list = this.assetService.landUsedPage(Long.valueOf(getCompanyId()));
        return getDataTable(list);
    }

    @GetMapping("house/xlsx")
    public void houseExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/房屋资产台账-template.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("房屋资产台账", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.houseExportList(Long.valueOf(getCompanyId())));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }

    @GetMapping("house/basic/page")

    public TableDataInfo houseBasicPage() {
        startPage();
        List<AssetStatisticsBasicVO> vos = this.assetService.houseBasicPage(Long.valueOf(getCompanyId()));
        return getDataTable(vos);
    }

    @GetMapping("house/used/page")
    public TableDataInfo houseUsedPage() {
        startPage();
        List<AssetStatisticsUsedVO> list = this.assetService.houseUsedPage(Long.valueOf(getCompanyId()));
        return getDataTable(list);
    }


    /**
     * 统计分析-合同分析
     * @return
     */
    @GetMapping("contract/analysis")
    public AjaxResult contractAnalysisCount(@RequestParam String contractType, @RequestParam("companyId") int companyId) {
        return AjaxResult.success(assetService.contractAnalysisCount(contractType, companyId));
    }

    /**
     * 统计分析-合同分析
     * @return
     */
    @GetMapping("contract/analysis/page")
    public TableDataInfo contractAnalysisPageList(@RequestParam String contractType, @RequestParam Date startTime, @RequestParam Date endTime, @RequestParam("companyId") int companyId) {
        startPage();
        return getDataTable(assetService.contractAnalysisPageList(contractType,companyId,contractType,startTime,endTime));
    }
    private Integer getCompanyId() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        Integer companyId = null;
        if (null != loginUser) {
            companyId = Math.toIntExact(loginUser.getUser().getDeptId());
        }
        return companyId;
    }


    @GetMapping("house/receipt/page")
    public TableDataInfo houseReceiptPage(){
        startPage();
        return getDataTable(assetService.getHouseReceiptList(getCompanyId()));
    }
    @GetMapping("house/receipt/xlsx")
    public void houseReceiptExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/房屋到账-template.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("房屋到账", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.getHouseReceiptList((getCompanyId())));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }

    @GetMapping("land/receipt/page")
    public TableDataInfo landReceiptPage(){
        startPage();
        return getDataTable(assetService.getLandReceiptList(getCompanyId()));
    }
    @GetMapping("land/receipt/xlsx")
    public void landReceiptExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/土地到账-template.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("土地到账", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.getLandReceiptList((getCompanyId())));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }

    @GetMapping("getBeOccupiedAsset/page")
    public TableDataInfo getBeOccupiedAsset(){
        startPage();
        return getDataTable(assetService.getBeOccupiedAsset(getCompanyId()));
    }

    @GetMapping("getBeOccupiedAsset/xlsx")
    public void getBeOccupiedAssetExport(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String resource = reportPath + "/template/被借用（占用）资产明细.xlsx";

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("被借用（占用）资产明细", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(resource)
                    .sheet()
                    /**
                     * 插入需要到处的数据源
                     */
                    .doFill(this.assetService.getBeOccupiedAsset((getCompanyId())));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            throw new RuntimeException("导出失败");
        }
    }
}
